<template>
  <e-cellbox middle class="img-code" :gutter="10" :class="inline?'img-code-inline':''">
    <e-cell-item>
      <el-input v-bind="$props" :action="null" :params="null" :code-icon="null" :img-key="null" :inline="null" v-on="$listeners">
        <template v-if="codeIcon" slot="prepend"><i class="iconfont" v-html="codeIcon"></i></template>
      </el-input>
    </e-cell-item>
    <e-cell-item v-loading="loading">
      <img v-if="src" alt="图片验证码" :src="src" @click="refresh" title="看不清楚？点击换一张"/>
      <span v-else>&nbsp;</span>
    </e-cell-item>
  </e-cellbox>
</template>

<script>
  import { Input } from '@element-ui'
  import {Cellbox, CellItem} from './cellbox'
  export default {
    componentName: 'EImgCode',
    components: {
      ElInput: Input,
      ECellbox: Cellbox,
      ECellItem: CellItem
    },
    props: {
      ...Input.props,
      placeholder: {
        type: String,
        default: '请输入图片验证码'
      },
      maxlength: {
        type: Number,
        default: 4
      },
      imgKey: {
        type: String,
        default: ''
      },
      inline: {
        type: Boolean,
        default: false
      },
      codeIcon: {
        type: String,
        default: '&#xe676;'
      },
      action: {
        default: '/guest/generateImgValidateCode'
      },
      params: {
        type: [Object, Function],
        default () {
          return {}
        }
      }
    },
    data () {
      return {
        src: '',
        loading: false
      }
    },
    mounted () {
      this.refresh()
    },
    methods: {
      refresh () {
        this.loading = true
        require.ensure([], (r) => {
          let options = {
            url: this.action,
            params: Object.assign({
              width: 120,
              height: 40,
              type: 1,
              time: new Date().getTime()
            }, this.params)
          }
          let fetch = require('fetch').default
          fetch(options).then((res) => {
            setTimeout(() => {
              this.src = res.data.image
              this.$emit('update:imgKey', res.data.key)
              this.loading = false
            }, 400)
          }).catch(() => {
            this.loading = false
          })
        })
      }
    }
  }
</script>
